package com.chefu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chefu.common.exception.CfException;
import com.chefu.common.exception.ExceptionEnum;
import com.chefu.common.pojo.PageResult;
import com.chefu.system.mapper.RoleMapper;
import com.chefu.system.pojo.Module;
import com.chefu.system.pojo.Role;
import com.chefu.system.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author goodgoodstudy
 * @since 2021-03-30
 */
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;


    @Override
    public PageResult<Role> findByPage(Integer page, Integer pageSize, String roleName) {
        IPage iPage = new Page(page, pageSize);

        QueryWrapper queryWrapper = Wrappers.query();

        if (roleName != null) {
            queryWrapper.like("role_name", roleName);
        }

        iPage = roleMapper.selectPage(iPage, queryWrapper);

        PageResult<Role> pageResult = new PageResult<>();
        pageResult.setItems(iPage.getRecords());
        pageResult.setTotal(iPage.getTotal());
        pageResult.setTotalPage(iPage.getPages());

        return pageResult;

    }

    @Override
    public void insert(Role role, List<Long> moduleIds) {
        try {

            roleMapper.insert(role);

            roleMapper.insertRoleAndModule(role.getRoleId(), moduleIds);

        } catch (Exception e) {
            e.printStackTrace();
            throw new CfException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    @Override
    public void updateRole(Role role, List<Long> moduleIds) {
        try {
            roleMapper.updateById(role);

            if (moduleIds != null) {
                roleMapper.deleteByRoleId(role.getRoleId());

                roleMapper.insertRoleAndModule(role.getRoleId(), moduleIds);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new CfException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }

    @Override
    public void delete(Long roleId) {

        try {
            roleMapper.deleteByRoleId(roleId);

            roleMapper.deleteById(roleId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CfException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }

    }


}
